//
//  YGGravityImageView.m
//  基本框架
//
//  Created by runone02 on 2018/8/21.
//  Copyright © 2018年 liqiyun. All rights reserved.
//
#import "YGGravityImageView.h"
#import "YGGravity.h"

#define SPEED 50

@implementation YGGravityImageView


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self configUI];
    }
    return self;
}

- (void)configUI{
    WeakSelf(weakSelf);
    _myImageView = [[UIImageView alloc]init];
    _myImageView.userInteractionEnabled = YES;
    [self addSubview:_myImageView];
     UILabel *la  = [[UILabel alloc]init];
    la.text = @"绘制数值";
    la.textColor = [UIColor redColor];
    la.font = TITLE_FONT(50);
    [_myImageView addSubview:la];
    [la mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(weakSelf.myImageView);
    }];
}

- (void)setImage:(UIImage *)image{
    _image = image;
    _myImageView.image = image;
    [_myImageView sizeToFit];
    _myImageView.frame = CGRectMake(0, 0, self.frame.size.height *(_myImageView.frame.size.width / _myImageView.frame.size.height), self.frame.size.height);
    _myImageView.center = CGPointMake(self.frame.size.width/2,self.frame.size.height/2);
}

- (void)startAnimate {
    float scrollSpeed = (_myImageView.frame.size.width - self.frame.size.width)/2/SPEED;
    [YGGravity sharedGravity].timeInterval = 0.1;
    
    [[YGGravity sharedGravity]startDeviceMotionUpdatesBlock:^(float x, float y, float z) {
        WeakSelf(weakSelf);
        [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeDiscrete animations:^{
            
            if (weakSelf.myImageView.frame.origin.x <=0 && weakSelf.myImageView.frame.origin.x >= self.frame.size.width - weakSelf.myImageView.frame.size.width){
                float invertedYRotationRate = y * -1.0;
                
                float interpretedXOffset = weakSelf.myImageView.frame.origin.x + invertedYRotationRate * (weakSelf.myImageView.frame.size.width/SCREEN_WIDTH) * scrollSpeed + weakSelf.myImageView.frame.size.width/2;
                
                weakSelf.myImageView.center = CGPointMake(interpretedXOffset, weakSelf.myImageView.center.y);
            }
            
            if (weakSelf.myImageView.frame.origin.x >0){
                weakSelf.myImageView.frame = CGRectMake(0, weakSelf.myImageView.frame.origin.y, weakSelf.myImageView.frame.size.width, weakSelf.myImageView.frame.size.height);
            }
            if (weakSelf.myImageView.frame.origin.x < self.frame.size.width - weakSelf.myImageView.frame.size.width){
                weakSelf.myImageView.frame = CGRectMake(self.frame.size.width - weakSelf.myImageView.frame.size.width, weakSelf.myImageView.frame.origin.y, weakSelf.myImageView.frame.size.width, weakSelf.myImageView.frame.size.height);
            }
        } completion:nil];        
    }];
}

- (void)stopAnimate {
    [[YGGravity sharedGravity] stop];
}

@end
